package handlers

import (
	"net/http"

	"dormitory/database"
	"dormitory/models"

	"github.com/gin-gonic/gin"
)

// GetStudents 获取学生列表
func GetStudents(c *gin.Context) {
	var students []models.Student
	result := database.DB.Find(&students)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取学生列表失败"})
		return
	}
	c.JSON(http.StatusOK, students)
}

// CreateStudent 创建新学生
func CreateStudent(c *gin.Context) {
	var student models.Student
	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	result := database.DB.Create(&student)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建学生信息失败"})
		return
	}

	c.JSON(http.StatusCreated, student)
}

// GetStudent 获取单个学生信息
func GetStudent(c *gin.Context) {
	id := c.Param("id")
	var student models.Student

	result := database.DB.First(&student, id)
	if result.Error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "学生不存在"})
		return
	}

	c.JSON(http.StatusOK, student)
}

// UpdateStudent 更新学生信息
func UpdateStudent(c *gin.Context) {
	id := c.Param("id")
	var student models.Student

	// 检查学生是否存在
	if err := database.DB.First(&student, id).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "学生不存在"})
		return
	}

	// 绑定更新数据
	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	// 更新学生信息
	database.DB.Save(&student)
	c.JSON(http.StatusOK, student)
}

// DeleteStudent 删除学生信息
func DeleteStudent(c *gin.Context) {
	id := c.Param("id")
	result := database.DB.Delete(&models.Student{}, id)

	if result.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, gin.H{"error": "学生不存在"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "学生信息已删除"})
}